<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">新增角色</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" prop="id" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" min-width="80px">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" prop="updateAt" align="center" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.roleDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createdAt" align="center" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updateAt" align="center" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.updateAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="success" size="small" @click="handleMenuAuthority(scope.row)">菜单权限</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :visible.sync="dialogMenuFormVisible" title="菜单权限" width="30%">
      <div class="tree-dialog">
        <el-tree ref="tree" :data="menus" :default-expanded-keys="[2]" :default-checked-keys="accessSelected" :props="defaultProps" :render-content="renderContent" show-checkbox node-key="id" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMenuFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateMenuAuthority">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px;">
        <el-form-item label="角色名称">
          <el-input v-model="temp.roleName" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="temp.roleDesc" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
	fetchRoleAjax,
	addRoleAjax,
	updateRoleAjax,
	delRoleAjax,
	fetchMenuAjax,
	fetchRoleAccessAjax,
	addRoleAccessAjax
	// updateRoleAccessAjax,
	// delRoleAccessAjax
} from "@/api/authority";
import waves from "@/directive/waves"; // Waves directive
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

export default {
	name: "RoleList",
	components: { Pagination },
	directives: { waves },
	data() {
		return {
			tableKey: 0,
			list: null,
			total: 0,
			listLoading: true,
			listQuery: {
				pageNum: 1,
				pageSize: 10
			},
			temp: {
				id: "",
				roleName: "",
				roleDesc: ""
			},
			menuTemp: {},
			dialogFormVisible: false,
			dialogMenuFormVisible: false,
			dialogStatus: "",
			textMap: {
				update: "编辑",
				create: "新增角色"
			},
			pvData: [],
			rules: {
				type: [
					{
						required: true,
						message: "type is required",
						trigger: "change"
					}
				],
				timestamp: [
					{
						type: "date",
						required: true,
						message: "timestamp is required",
						trigger: "change"
					}
				],
				title: [
					{
						required: true,
						message: "title is required",
						trigger: "blur"
					}
				]
			},
			downloadLoading: false,
			menus: [],
			accessSelected: null,
			defaultProps: {
				children: "children",
				label: "label"
			}
		};
	},
	created() {
		this.getList();
		// this.getMenuList();
	},
	methods: {
		getList() {
			this.listLoading = true;
			fetchRoleAjax(this.listQuery).then(response => {
				this.list = response.data.data.pageData;
				this.total = response.data.data.maxCount;
				this.listLoading = false;
			});
		},
		resetTemp() {
			this.temp = {
				id: undefined,
				roleName: "",
				roleDesc: ""
			};
		},
		handleCreate() {
			this.resetTemp();
			this.dialogStatus = "create";
			this.dialogFormVisible = true;
		},
		createData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					addRoleAjax(this.temp).then(() => {
						this.list.unshift(this.temp);
						this.dialogFormVisible = false;
						this.getList();
						this.$notify({
							title: "成功",
							message: "创建成功",
							type: "success",
							duration: 2000
						});
					});
				}
			});
		},
		handleUpdate(row) {
			this.temp = Object.assign({}, row); // copy obj
			this.dialogStatus = "update";
			this.dialogFormVisible = true;
		},
		handleMenuAuthority(row) {
			this.menuTemp = Object.assign({}, { roleId: row.id }); // copy obj
			this.dialogMenuFormVisible = true;
			this.getMenuList(row.id);
		},
		updateData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					const tempData = Object.assign({}, this.temp);
					tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
					updateRoleAjax(tempData).then(() => {
						for (const v of this.list) {
							if (v.id === this.temp.id) {
								const index = this.list.indexOf(v);
								this.list.splice(index, 1, this.temp);
								break;
							}
						}
						this.dialogFormVisible = false;
						this.getList();
						this.$notify({
							title: "成功",
							message: "更新成功",
							type: "success",
							duration: 2000
						});
					});
				}
			});
		},
		handleDelete(row) {
			this.$confirm("确认删除该条数据吗?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				delRoleAjax(row).then((res) => {
					// const index = this.list.indexOf(row);
					// this.list.splice(index, 1);
					if (res.data.code !== 0) {
						this.$message({
							message: '删除失败',
							type: 'error',
							duration: 5 * 1000
						})
						return;
					}
					this.getList();
					this.$notify({
						title: "成功",
						message: "删除成功",
						type: "success",
						duration: 2000
					});
				});
			});
		},
		updateMenuAuthority() {
			this.menuTemp.menuIds = this.$refs.tree.getCheckedKeys();
			console.log(this.menuTemp, "mmm");
			addRoleAccessAjax(this.menuTemp).then((data) => {
				// for (const v of this.list) {
				// 	if (v.id === this.temp.id) {
				// 		const index = this.list.indexOf(v);
				// 		this.list.splice(index, 1, this.temp);
				// 		break;
				// 	}
				// }
				this.dialogMenuFormVisible = false;
				this.$notify({
					title: "成功",
					message: "更新成功",
					type: "success",
					duration: 2000
				});
			});
		},
		getMenuList(roleId) {
			Promise.all([fetchMenuAjax(), fetchRoleAccessAjax({ roleId })]).then((data) => {
				this.menus = JSON.parse(JSON.stringify(data[0].data.data));
				this.accessSelected = data[1].data.data;
			})
			// fetchMenuAjax().then(response => {
			// 	this.menus = JSON.parse(JSON.stringify(response.data.data));
			// });
			// fetchRoleAccessAjax({ roleId }).then(response => {
			// 	console.log(response, 'kkk333')
			// 	this.accessSelected = response.data.data;
			// });
		},
		renderContent(h, { node, data, store }) {
			return (
				<span class='custom-tree-node'>
					<span>{data.moduleName}</span>
				</span>
			);
		}
	}
};
</script>
<style lang="scss">
.tree-dialog {
	height: 280px;
	overflow: auto;
}
</style>
